import axios from 'axios'
import { defineStore } from 'pinia'

const useMenuBadgeStore = defineStore(
  'menuBadge',
  () => {
    const dot = ref(true)
    const number1 = ref(0) // 初始值改为0更合理
    const number2 = ref(0) // 初始值改为0更合理
    const text = ref('热门')

    // 新增获取未读数的方法
    const fetchUnreadNumber = async () => {
      try {
        const response = await axios.post(
          'https://www.cqwuyang.cn/ElectricManageService/feedback/findUnreadBackend',
          { feedbackType: 1 },
        )
        number1.value = response.data.data?.unreadNum || 0
      }
      catch (error) {
        console.error('获取未读数失败:', error)
        number1.value = 0
      }
      try {
        const response = await axios.post(
          'https://www.cqwuyang.cn/ElectricManageService/feedback/findUnreadBackend',
          { feedbackType: 2 },
        )
        number2.value = response.data.data?.unreadNum || 0
      }
      catch (error) {
        console.error('获取未读数失败:', error)
        number2.value = 0
      }
    }

    // 新增自动轮询方法
    const startAutoPolling = (interval = 1000) => {
      fetchUnreadNumber() // 立即执行第一次
      const timer = setInterval(fetchUnreadNumber, interval)
      return () => clearInterval(timer) // 返回清除定时器的方法
    }

    function switchDot() {
      dot.value = !dot.value
    }

    function setText(val: string) {
      text.value = val
    }

    return {
      dot,
      number1,
      number2,
      text,
      switchDot,
      setText,
      fetchUnreadNumber, // 暴露请求方法
      startAutoPolling, // 暴露轮询方法
    }
  },
)

export default useMenuBadgeStore
